//
//  VideoPlayerViewController.m
//  GenericProject
//
//  Created by 皮蛋菌 on 2023/5/6.
//  Copyright © 2023 漠然丶情到深处. All rights reserved.
//

#import "VideoPlayerViewController.h"
#import <AVKit/AVKit.h>
#import <MediaPlayer/MediaPlayer.h>
#import "PlayerSkinView.h"
#import "VolumeBrightnessView.h"

@interface VideoPlayerViewController ()

@property(nonatomic,strong)AVPlayer *player;
@property(nonatomic,strong)AVPlayerLayer *playerLayer;
@property(nonatomic,assign)BOOL isFullScreen;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)NSTimer *brightnessTimer;
@property(nonatomic,strong)NSTimer *volumeTimer;
@property(nonatomic,strong)PlayerSkinView *playerSkinView;
@property(nonatomic,strong)VolumeBrightnessView *brightnessView;
@property(nonatomic,strong)VolumeBrightnessView *volumeView;
@property(nonatomic,assign)CGFloat screenLight;
@property(nonatomic,assign)CGFloat screenVolume;

@end

@implementation VideoPlayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = LSBlackColor;
    // Do any additional setup after loading the view.
    [self startTimer];
    [self createSubViews];
}

- (void)createSubViews {
    LSWeakSelf(self);
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:self.videoURL];
    NSString *videoName = [[self.videoURL lastPathComponent] stringByDeletingPathExtension];
        
    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    [self.view.layer addSublayer:self.playerLayer];
    
    self.playerSkinView = [[PlayerSkinView alloc]init];
    [self.view addSubview:self.playerSkinView];
    [self.playerSkinView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.left.equalTo(self.view).offset(0);
        make.size.mas_equalTo(CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height));
    }];
    
    self.playerSkinView.titleLabel.text = videoName;
    
    self.playerSkinView.blackActionBlock = ^{
        LSStrongSelf(self);
        [AppDelegate shareAppDelegate].launchScreen = NO;
        [self dismissViewControllerAnimated:YES completion:nil];
    };
    
    self.playerSkinView.playActionBlock = ^(BOOL isPlayer) {
        LSStrongSelf(self);
        if (isPlayer) {
            [self.player pause];
            [self stopTimer];
        } else {
            [self.player play];
            [self startTimer];
        }
    };
    
    self.playerSkinView.progressChangeBlock = ^{
        LSStrongSelf(self);
        CMTime duration = self.player.currentItem.duration;
        double seconds = CMTimeGetSeconds(duration);
        double time = seconds * self.playerSkinView.progressSlider.value;
        [self.player seekToTime:CMTimeMakeWithSeconds(time, 1)];
    };
    
    self.playerSkinView.rateActionBlock = ^(UIButton * _Nonnull rateButton) {
        LSStrongSelf(self);
        float rate = self.player.rate;
        if (rate == 1.0) {
            rate = 1.5;
            [rateButton setTitle:@"1.5" forState:UIControlStateNormal];
        } else if (rate == 1.5) {
            rate = 2.0;
            [rateButton setTitle:@"2.0" forState:UIControlStateNormal];
        } else {
            rate = 1.0;
            [rateButton setTitle:@"1.0" forState:UIControlStateNormal];
        }
        [self.player setRate:rate];
    };
    
    self.playerSkinView.fullScreenActionBlock = ^(BOOL isFull) {
        LSStrongSelf(self);
        self.isFullScreen = isFull;
        [self switchOrientationWithLaunchScreen:isFull];
    };
    
    // 创建亮度调节的 UI
    self.brightnessView = [[VolumeBrightnessView alloc] init];
    self.brightnessView.alpha = 0;
    self.brightnessView.layer.masksToBounds = YES;
    self.brightnessView.layer.cornerRadius = LSSYRealValue(2);
    [self.view addSubview:self.brightnessView];
    [self.brightnessView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY);
        make.size.mas_offset(CGSizeMake(LSSYRealValue(150), LSSYRealValue(20)));
    }];
    // 创建音量调节的 UI
    self.volumeView = [[VolumeBrightnessView alloc] init];
    self.volumeView.alpha = 0;
    self.volumeView.layer.masksToBounds = YES;
    self.volumeView.layer.cornerRadius = LSSYRealValue(2);
    [self.view addSubview:self.volumeView];
    [self.volumeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY);
        make.size.mas_offset(CGSizeMake(LSSYRealValue(150), LSSYRealValue(20)));
    }];
    // 更新音量和亮度 UI 的进度
    [self updateBrightnessUI];
    [self updateVolumeUI];
    
    [self.player play];
    
    self.playerSkinView.durationLabel.text = [self formatTime:CMTimeGetSeconds(playerItem.duration)];

    
    // Add tap gesture recognizer for showing/hiding controls
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
    [self.view addGestureRecognizer:tapGestureRecognizer];

    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
    [self.view addGestureRecognizer:panGestureRecognizer];

    [self.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1, 10) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        LSStrongSelf(self);
        [self updateUI];
    }];

    //监听播放状态，结束时，重置进度条位置，播放状态，按钮状态，播放进度
    [[NSNotificationCenter defaultCenter] addObserverForName:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        LSStrongSelf(self);
        // 播放结束，重置状态和进度条
        [self.player seekToTime:kCMTimeZero];
        [self.player pause];
        [self.playerSkinView.progressSlider setValue:0.0 animated:YES];
        self.playerSkinView.playButton.selected = YES;
    }];
}

//皮肤点击方法
- (void)handleTapGesture:(UITapGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.state == UIGestureRecognizerStateRecognized) {
        if (self.playerSkinView.alpha == 1.0) {
            [self hideControls];
        } else {
            [self showControls];
        }
    }
}

- (void)startTimer {
    [self stopTimer];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(hideControls) userInfo:nil repeats:NO];
}

- (void)stopTimer {
    [self.timer invalidate];
    self.timer = nil;
}

- (void)showControls {
    [UIView animateWithDuration:0.25 animations:^{
        self.playerSkinView.alpha = 1.0;
    } completion:^(BOOL finished) {
        [self startTimer];
    }];
}

- (void)hideControls {
    [UIView animateWithDuration:0.25 animations:^{
        self.playerSkinView.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self stopTimer];
    }];
}

//更新播放进度与播放时间
- (void)updateUI {
    double durationSeconds = CMTimeGetSeconds(self.player.currentItem.duration);
    double timeSeconds = CMTimeGetSeconds(self.player.currentItem.currentTime);

    CMTime duration = self.player.currentItem.duration;
    CGFloat durationInSeconds = duration.value / duration.timescale;
    // 更新播放时间
    self.playerSkinView.timeLabel.text = [self timeStringFromSeconds:CMTimeGetSeconds(self.player.currentTime)];
    self.playerSkinView.durationLabel.text = [self timeStringFromSeconds:durationInSeconds];
    self.playerSkinView.progressSlider.value = timeSeconds / durationSeconds;
}

- (NSString *)timeStringFromSeconds:(CGFloat)seconds {
    NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
    formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;
    formatter.allowedUnits = NSCalendarUnitMinute | NSCalendarUnitSecond;
    return [formatter stringFromTimeInterval:seconds];
}

- (NSString *)formatTime:(double)time {
    NSInteger minutes = (NSInteger)time / 60;
    NSInteger seconds = (NSInteger)time % 60;
    return [NSString stringWithFormat:@"%02ld:%02ld", (long)minutes, (long)seconds];
}

- (void)dealloc {
    [self.timer invalidate];
    [self.brightnessTimer invalidate];
    [self.volumeTimer invalidate];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/// 切换设备方向
- (void)switchOrientationWithLaunchScreen:(BOOL)isLaunchScreen {
    if (isLaunchScreen) {
        // 全屏操作
        [AppDelegate shareAppDelegate].launchScreen = YES;
    } else {
        // 退出全屏操作
        [AppDelegate shareAppDelegate].launchScreen = NO;
    }

    if (@available(iOS 16.0, *)) {
        [self setNeedsUpdateOfSupportedInterfaceOrientations];
        NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
        UIWindowScene *scene = [array firstObject];
        // 屏幕方向
        UIInterfaceOrientationMask orientation = isLaunchScreen ? UIInterfaceOrientationMaskLandscapeRight : UIInterfaceOrientationMaskPortrait;
        UIWindowSceneGeometryPreferencesIOS *geometryPreferencesIOS = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:orientation];
        // 开始切换
        [scene requestGeometryUpdateWithPreferences:geometryPreferencesIOS errorHandler:^(NSError * _Nonnull error) {
                
        }];
    } else {
        [self swichToNewOrientation:isLaunchScreen ? UIInterfaceOrientationLandscapeRight : UIInterfaceOrientationPortrait];
    }
}

/// iOS16 之前进行横竖屏切换方式
/// - Parameter interfaceOrientation: 需要切换的方向
- (void)swichToNewOrientation:(UIInterfaceOrientation)interfaceOrientation {
    NSNumber *orientationTarget = [NSNumber numberWithInteger:interfaceOrientation];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    BOOL isLaunchScreen = NO;
    if (@available(iOS 16.0, *)) {
        NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
        UIWindowScene *scene = [array firstObject];
        isLaunchScreen = scene.interfaceOrientation == UIInterfaceOrientationLandscapeRight;
    } else {
        isLaunchScreen = [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft;
    }
    
    [self updateViewWithIsLaunchScreen:isLaunchScreen size:size];
}

- (void)updateViewWithIsLaunchScreen:(BOOL)isLaunchScreen size:(CGSize)size {
    self.playerLayer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    [self.playerSkinView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.left.equalTo(self.view).offset(0);
        make.size.mas_equalTo(CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height));
    }];
}

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (self.isFullScreen) {
        return UIInterfaceOrientationMaskLandscapeRight;
    }
    return UIInterfaceOrientationMaskPortrait;
}

// 更新音量 UI 的进度
- (void)updateVolumeUI {
    CGFloat volume = [self getCurrentVolume];
    [self.volumeView setProgress:volume];
}

// 更新亮度 UI 的进度
- (void)updateBrightnessUI {
    CGFloat brightness = [UIScreen mainScreen].brightness;
    [self.brightnessView setProgress:brightness];
}

// 获取当前音量
- (CGFloat)getCurrentVolume {
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    CGFloat currentVolume = audioSession.outputVolume;
    return currentVolume;
}

// 手势处理方法
- (void)handlePanGesture:(UIPanGestureRecognizer *)gestureRecognizer {
    CGPoint translation = [gestureRecognizer translationInView:self.view];
    CGPoint location = [gestureRecognizer locationInView:self.view];
    CGFloat screenWidth = CGRectGetWidth([UIScreen mainScreen].bounds);
    CGFloat screenHeight = CGRectGetHeight([UIScreen mainScreen].bounds);
    CGFloat deltaBrightness = 0.5; // 亮度变化步进值
    CGFloat deltaVolume = 0.2; // 音量变化步进值

    if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {
        // 判断手势滑动方向
        if (location.x < screenWidth / 2) { // 左半屏幕滑动，调节亮度
            CGFloat delta = -translation.y / screenHeight;
            self.screenLight = [UIScreen mainScreen].brightness;
            self.screenLight += deltaBrightness * delta;
            self.screenLight = self.screenLight > 1.0 ? 1.0 : self.screenLight;
            self.screenLight = self.screenLight < 0.0 ? 0.0 : self.screenLight;
            [[UIScreen mainScreen] setBrightness:self.screenLight];
            [self adjustBrightnessByDelta:self.screenLight];
            
            if (self.brightnessView.alpha == 1.0) {
                [self hideBrightnessControls];
            } else {
                [self showBrightnessControls];
            }
            if (self.volumeView.alpha == 1.0) {
                self.volumeView.alpha = 0;
            }
        } else { // 右半屏幕滑动，调节音量
            CGFloat delta = -translation.y / screenHeight;
            self.screenVolume = self.player.volume;
            self.screenVolume += deltaVolume * delta;
            self.screenVolume = self.screenVolume > 1.0 ? 1.0 : self.screenVolume;
            self.screenVolume = self.screenVolume < 0.0 ? 0.0 : self.screenVolume;
            self.player.volume = self.screenVolume;
            [self adjustVolumeByDelta:self.screenVolume];
            
            if (self.volumeView.alpha == 1.0) {
                [self hideVolumeControls];
            } else {
                [self showVolumeControls];
            }
            if (self.brightnessView.alpha == 1.0) {
                self.brightnessView.alpha = 0;
            }
        }
    }else if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
        
    }
}

//  调节亮度
- (void)adjustBrightnessByDelta:(CGFloat)delta {
    [self.brightnessView setProgress:delta];
}

// 根据增量调整音量
- (void)adjustVolumeByDelta:(CGFloat)delta {
    [self.volumeView setProgress:delta];
}

//亮度调节UI动画
- (void)showBrightnessControls {
    [UIView animateWithDuration:0.25 animations:^{
        self.brightnessView.alpha = 1.0;
    } completion:^(BOOL finished) {
        [self startBrightnessTimer];
    }];
}

- (void)hideBrightnessControls {
    [UIView animateWithDuration:0.25 animations:^{
        self.brightnessView.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self stopBrightnessTimer];
    }];
}

- (void)startBrightnessTimer {
    [self stopBrightnessTimer];
    self.brightnessTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(hideBrightnessControls) userInfo:nil repeats:NO];
}

- (void)stopBrightnessTimer {
    [self.brightnessTimer invalidate];
    self.brightnessTimer = nil;
}

//音量调节UI动画
- (void)showVolumeControls {
    [UIView animateWithDuration:0.25 animations:^{
        self.volumeView.alpha = 1.0;
    } completion:^(BOOL finished) {
        [self startVolumeTimer];
    }];
}

- (void)hideVolumeControls {
    [UIView animateWithDuration:0.25 animations:^{
        self.volumeView.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self stopVolumeTimer];
    }];
}

- (void)startVolumeTimer {
    [self stopVolumeTimer];
    self.volumeTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(hideVolumeControls) userInfo:nil repeats:NO];
}

- (void)stopVolumeTimer {
    [self.volumeTimer invalidate];
    self.volumeTimer = nil;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
